package org.biodas.jdas.dassources.utils;

import java.util.List;

import org.biodas.jdas.dassources.Capabilities;
import org.biodas.jdas.exceptions.ValidationException;
import org.biodas.jdas.schema.sources.CAPABILITY;
import org.biodas.jdas.schema.sources.VERSION;

public class VersionAdapter {

	VERSION version;
	public VersionAdapter(VERSION version){
		this.version=version;
	}
	/**
	 * Get the data source uri e.g. http://das.sanger.ac.uk/das/structure
	 * 
	 * @return
	 * @throws ValidationException
	 */
	public String getOriginalDataSourceUri() throws ValidationException {
		// System.out.println("qUri="+queryUri);
		return getSourceUriFromQueryUri(version.getCAPABILITY());
	}

	
	/**
	 * 
	 * @param list
	 * @return
	 */
	private String getSourceUriFromQueryUri(List<CAPABILITY> list)
			throws ValidationException {
		String queryUri=getQueryUriFromCaps(list);
		//System.out.println("quri="+queryUri);
		
		String dasString = "/das/";
		int dasIndex = queryUri.indexOf(dasString);
		// System.out.println("dasIndex="+dasIndex);
		if (dasIndex == -1) {
			dasString = "/das1/";
			dasIndex = queryUri.indexOf(dasString);
		}
		if (this.hasBigFileFormat()) {
			return queryUri;
		}
		if (dasIndex == -1) {
			throw new ValidationException(
					"the das source query_uri must contain a /das/ queryUri="
							+ queryUri);
		}
		String includingDAS = queryUri.substring(0,
				dasIndex + dasString.length());
		String afterDas = queryUri.substring(dasIndex + dasString.length(),
				queryUri.length());
		String sourceUri = "";
		if (afterDas.contains("/")) {
			sourceUri = includingDAS
					+ afterDas.substring(0, afterDas.indexOf("/"));
		} else {
			sourceUri = includingDAS + afterDas;
		}
		// System.out.println("sourceUri="+sourceUri);
		return sourceUri;

	}
	
	private String getQueryUriFromCaps(List<CAPABILITY> capList){
		for(CAPABILITY cap:capList){
			if((cap.getQueryUri()!=null) && (!cap.getQueryUri().equals(""))){
				return cap.getQueryUri();
			}
		}
		return "";
	}
	
	public boolean hasBigFileFormat() {
		

			List<CAPABILITY> caps = version.getCAPABILITY();
			for (CAPABILITY cap : caps) {
				if (Capabilities.isBigFileFormat(cap.getType().substring(5,
						cap.getType().length()))) {
					System.out.println(cap.getType() + "Big file format found");
					return true;
				}
			}
		
		return false;
	}
}
